﻿using System;
using System.ComponentModel;

namespace ImageConverter.Pooling
{
    public class Dimensions : INotifyPropertyChanged
    {
        public static readonly Dimensions Empty = DimensionsPool.Create(0, 0);

        internal Dimensions(int width, int height)
        {
            Width = width;
            Height = height;
        }

        public int Width
        {
            get
            {
                return width;
            }
            private set
            {
                width = value;
                OnPropertyChanged("Width");
            }
        }

        public int Height
        {
            get
            {
                return height;
            }
            private set
            {
                height = value;
                OnPropertyChanged("Height");
            }
        }

        public override string ToString()
        {
            return Width.ToString() + 'x' + Height.ToString() + '@' + String.Format("{0:0.000}", CalculateAspect());
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            Dimensions dim = obj as Dimensions;
            if (dim == null)
                return false;

            return dim.Width == Width && dim.Height == Height;
        }

        public override int GetHashCode()
        {
            if (fHashCode == 0)
            {
                fHashCode = 17 + 35 * Width.GetHashCode();
                fHashCode += 19 * Height.GetHashCode();
            }

            return fHashCode;
        }

        public double CalculateAspect()
        {
            return (double)Width / (double)Height;
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

        #region Private fields

        private int width;
        private int height;
        private int fHashCode;

        #endregion
    }
}
